<script type="text/javascript">
/*Api根域名*/
const  BaseUrl = 'https://api.xiaomashengxian.com';
var str = getCookie('user_cart_id');
if (! str) {
    str = randomString();
   /* alert(str)*/
    setCookie('user_cart_id', str);
}
var goods_num ;
/*根域名*/
const  HostUrl = window.location.protocol+'//'+window.location.host;
//const  HostUrl = 'http://localhost:81';
function getRandColor () {
  var temp = Math.round(Math.random() * 20)
  return temp
}
//写Cookie配置路径域名
function setCookie(cname, cvalue, exdays,path,domain) {
	var d = new Date();
	d.setTime(d.getTime() + (exdays * 60 * 60 * 1000));
	var expires = "expires=" + d.toUTCString();
	document.cookie = cname + "=" + cvalue + "; " + expires+
        ((path) ?  "; path=" + path : "; path=/")+
        ((domain) ? "; domain=" + domain : "");
}
//读Cookie
function getCookie(cname) {
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1);
		if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
	}
	return "";
}		

function merge_array(a,b){
	for(var i in b){
		a.push(b[i])
	}
}

// 获取数组元素的实际个数
function arrayCount(obj) {
    var objType = typeof obj;
    if(objType == "string"){
        return obj.length;
    }else if(objType == "object"){
        var objLen = 0;
        for(var i in obj){
            objLen++;
        }
        return objLen;
    }
    return false;
}

// 判断数组是否存在某个元素
function isInArray(val, arr) {
    var i = arr.length;
    while (i--) {
        if (arr[i] == val) {
            return true;
        }
    }
    return false;
}


//url转换
function  parseParam(param, key, encode) {  
  if(param==null) return '';  
  var paramStr = '';  
  var t = typeof (param);  
  if (t == 'string' || t == 'number' || t == 'boolean') {  
    paramStr += '&' + key + '=' + ((encode==null||encode) ? encodeURIComponent(param) : param);  
  } else {  
    for (var i in param) {  
      var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);  
      paramStr += parseParam(param[i], k, encode);  
    }  
  }  
  return paramStr;  
};


// 删除数组指定的元素
function removeByValue(arr, val) {
    for(var i=0; i<arr.length; i++) {
        if(arr[i] == val) {
            arr.splice(i, 1);
            return arr;
        }
    }
}

//时间戳格式转换
function formatDate(date, fmt){
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
    }
    return fmt;
};

function padLeftZero(str) {
    return ('00' + str).substr(str.length);
};

/*购物车特效首页*/
function get_te(img){
    var offset = $('#foot_li .te_time').offset();
   /* var img = $('.img_l1').attr('src');*/
    /*console.log('fly.................')*/
    var flyer = $('<img class="flyer-img" src="' + img + '">'); //抛物体对象  //抛物体对象
    flyer.fly({
        start:{
            left:event.pageX,
            top:event.pageY
        },
        end:{
            left:offset.left,
            top:offset.top
        },
        onEnd:function(){
            /*console.log('成功加入购物车')*/
            flyer.remove();//销毁实例
        },

    })
}
/*分类列表购物车*/
function get_te1(aa){
    let offset = $('.te_1').offset();
    let img = $('#img'+aa).attr('src');

    /*  console.log('fly.................')*/
    let flyer = $('<img class="flyer-img" src="' + img + '">'); //抛物体对象  //抛物体对象
    let $top=$(window).scrollTop();
    flyer.fly({
        start:{
            left:event.pageX,
            top:event.pageY-$top,
        },
        end:{
            left:offset.left,
            top:offset.top-$top,
        },
        onEnd:function(){
           /* console.log('成功加入购物车');*/
            flyer.remove();//销毁实例
        },

    })
}
//首页请求接口 
function getList(e,mode,stat){

    let url  = BaseUrl+'/mobile/api/v1/Index.php?mode='+mode;
    let Data = dataParam();

    e.$ajax.post(url, Data).then((res) => {
        let temp = res.data;
        if(temp.code == 200){
            if(stat == 1){
                e.tag1_ad    = temp.data.ad[0];
                e.tag1_list  = temp.data.list;
            }
            if(stat == 2){
                e.tag2_ad    = temp.data.ad[0];
                e.tag2_list  = temp.data.list;
            }
            if(stat == 3){
                e.tag3_ad    = temp.data.ad[0];
                e.tag3_list  = temp.data.list;
            }
            if(stat == 4){
                e.tag4_list    = temp.data;
            }
            if(stat==5){
                e.tag4_ad      =temp.data
            }
        }else{
            console.log(temp.msg);        
        }                 
     })

}

//购物车
function addCart(e,goods_id,number,gift=''){
	e.$http.jsonp(BaseUrl+'/mobile/api/v1/Flow.php?mode=addToCart',
		{
		    params: {
		        goods_id:goods_id,
                goods_num:number,
                gift_ids:gift,
                uid:getCookie('uid'),
                time:getCookie('time'),
                token:getCookie('token'),
                session_id:getCookie('user_cart_id'),
            },
            jsonp:'callback'
		}
	).then(function (res) {
		if(res.body.code == 200){
            goods_nums(e);
		}else{
			console.log(res.body.msg);
		}
	});
}

//最新购物车
function goods_nums(e){
    e.$http.jsonp(
        e.GLOBAL.BaseUrl+'/mobile/api/v1/Flow.php?mode=getCartNum',
        {
            params: {
                session_id:getCookie('user_cart_id'),
            },
            jsonp:'callback'
        },
    ).then(function(res){
        if (res.body.code == 200) {
            setCookie('goods_num',res.body.data.number);
            if(res.body.data.number>0){
                $('.times').css({'visibility':'visible'})
                $('.times').html(res.body.data.number);
            }else{

            }
        }
    })
}

//跳转登录
function back_login(e){
    var url = e.$route.fullPath;
    e.$router.push('/login?back_url='+url);
}

//回退个人中心
function back_center(e){
    var url = e.$route.fullPath;
    e.$router.push('/center?back_url='+url);
}


//个人中心异常处理
function center_error(e,data){
    if(data.code == 201){
         back_center(e);
    }else{
        alert(data.msg);        
    }
}

//商品访问记录
function guest(e){

    let temp = [];
    temp['guest']    = getCookie('user_cart_id');//e.guest_token;
    temp['url']      = e.$route.fullPath;
    temp['type']     = e.guest_type;
    temp['value']    = e.guest_val;

    let url  = BaseUrl+'/mobile/api/v1/Source.php?mode=guest';
    let Data = dataParam(temp);
    e.$ajax.post(url, Data).then((res) => {
      console.log(res.data.msg);   
    })
}

//data用户基本信息
function dataParam(temp = []){

    let user = []; 
    user['uid']   = getCookie('uid');
    user['time']  = getCookie('time');
    user['token'] = getCookie('token');

    //追加参数
    if(temp){
        for(var i in temp){
           user[i]   = temp[i];
        }
    }

    let Param = parseParam(user);
    Param = Param.substr(1);
    
    return Param;
}

//表单写入用户基本信息
function formParam(temp = {}){

    let formData = new FormData();
    formData.append('uid', getCookie('uid'));
    formData.append('time', getCookie('time'));
    formData.append('token', getCookie('token'));

    //追加参数
    if(temp){
        for(var i in temp){
           formData.append(i,temp[i]);
        }
    }

    return formData;
}

// 生成随机字符串
function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

export default
{
    BaseUrl,
    HostUrl,
    getRandColor,
    setCookie,
    getCookie,
    addCart,
    merge_array,
    arrayCount,
    isInArray,
    parseParam,
    removeByValue,
    formatDate,
    getList,
    back_login,
    back_center,
    center_error,
    guest,
    dataParam,
    formParam,
    get_te,
    get_te1,
    goods_nums,
    goods_num,
}
</script>
